<?php
/*
 * @Author: zeyudada
 * @Date: 2022-02-12 21:00:11
 * @LastEditTime: 2022-04-07 22:17:00
 * @Description: 通用函数集合
 * @Q Q: zeyunb@vip.qq.com(1776299529)
 * @E-mail: admin@zeyudada.cn
 * 
 * Copyright (c) 2022 by zeyudada, All Rights Reserved. 
 */

/**
 * @description: 获取平均分前几的用户
 * @param {int} $limit
 * @return {array} 分数从高到低排列的数组
 */
function rank($limit){
	global $DB;
    $answers = $DB->getAll("SELECT userid,correct,user.name FROM `answer` join `user` on user.id = answer.userid");
    rsort($answers);
	$rank = array();
    foreach ($answers as $answer) {
        # 排名
        $rank[$answer['userid']]['count'] = ($rank[$answer['userid']]['count'] > 0 ? $rank[$answer['userid']]['count'] : 0) + $answer['correct'];
        $rank[$answer['userid']]['num']++;
        $rank[$answer['userid']]['name'] = $answer['name'];
    }

	$i = 0;
    foreach ($rank as $k) {
        $i++;
        if ($i > $limit) break;
        $top[$i] = $k;
        $top[$i]['score'] = $k['count'] / $k['num'];
    }
    array_multisort(array_column($rank, 'count'), SORT_DESC, $rank);
	return $top;
}

/**
 * @description: 用于输出json结果
 * @param {array} $json 输入的数组
 */
function json($json = [])
{
	@header('Content-Type: application/json');
	unset($_SESSION['code']);
	exit(json_encode($json)); //传参
}

/**
 * @description: 获取客户端真实IP
 * @return {string} 用户IP
 */
function getip()
{
	if (getenv('HTTP_CLIENT_IP')) {
		$ip = getenv('HTTP_CLIENT_IP');
	}
	if (getenv('HTTP_X_REAL_IP')) {
		$ip = getenv('HTTP_X_REAL_IP');
	} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
		$ip = reset(explode(',', getenv('HTTP_X_FORWARDED_FOR')));
	} elseif ($_SERVER['REMOTE_ADDR']) {
		$ip = $_SERVER['REMOTE_ADDR'];
	} else {
		$ip = '0.0.0.0';
	}

	return $ip;
}
